package map.android.baidu.carpool.page.home;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;
import com.ant.liao.GifView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import map.android.baidu.carpool.Config;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.OrderDetailData;
import map.android.baidu.carpool.data.impl.OrderFinishData;
import map.android.baidu.carpool.model.URLModel;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.page.pay.CreateCarerCommentPage;
import map.android.baidu.carpool.page.pay.OrderPayPage;
import map.android.baidu.carpool.page.usercenter.EvaluateDriverPage;
import map.android.baidu.carpool.page.usercenter.UserInfoPage;
import map.android.baidu.carpool.response.OrderDetailResponse;
import map.android.baidu.carpool.response.OrderFinishResponse;
import map.android.baidu.carpool.setting.UserInfoSetting;
import map.android.baidu.carpool.utils.CarpoolAlertDialog;
import map.android.baidu.carpool.utils.CarpoolOkCancelDialog;
import map.android.baidu.carpool.utils.NumberUtil;
import map.android.baidu.carpool.utils.StatisticsUtil;
import map.android.baidu.carpool.utils.TimeUtil;
import map.android.baidu.carpool.utils.TitleHelpler;
import map.android.baidu.carpool.utils.ToastForCarpool;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshBase;
import map.android.baidu.carpool.widget.pulltorefresh.library.PullToRefreshScrollView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by zhaoyangyang on 2015/3/31.
 */
public class OrderDetailPage extends CarpoolBasePage implements View.OnClickListener {

    private View mView = null;
    private TitleHelpler mTitleHelper = null;
    private TextView mDriverName = null;
    private TextView mDriverInfo = null;
    private ImageView mOneCarPic = null;
    private ImageView mtwoCarPic = null;
    private TextView mTimeTv = null;
    private TextView mFromTV = null;
    private TextView mToTv = null;
    private RatingBar mRatingBar = null;
    private TextView mFeeTv = null;

    private LinearLayout mGoTo = null;
    private TextView mPayTV = null;

    private String orderId = "";
    private int nowOrderIdStatus = -1;
    private String desc = "";
    private OrderDetailResponse mOrderDetailResponse = null;
    private ImageLoader mImageLoader = null;
    private DisplayImageOptions options;

    private String mDriverMobile = "";

    private LinearLayout mParentLin = null;
    private View viewChildDriverInfo = null;
    private View viewFromAndToInfo = null;
    private boolean mNeedRefresh = true;
    private LinearLayout mCallPhone = null;
    private LinearLayout mGoToContainLin = null;
    private LinearLayout mPayTipLin = null;
    private LinearLayout mOrderStatusLin = null;
    private GifView mTimerGiftView = null;
    private TextView mOrderDesc = null;
    private ProgressBar mTimerProgressBar = null;
    private TextView mDriverJoin = null;
    private TextView mCompleteInfo = null;
    private TextView mPatTip = null;

    private long mCurrentSystem = 0L;
    private long mPayEndTime = 0L;
    private long mPayStartTime = 0L;

    private long mSpareTime = 0L;
    private long mDelayMills;
    private int mCount = 100;
    private boolean isProcessThread = false;
    private PullToRefreshScrollView mPullToRefreshScrollView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (this.getArguments() != null) {
            this.orderId = getArguments().getString("orderId");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (isNavigateBack()) {
            if (getBackwardArguments() != null) {
                if (getBackwardArguments().containsKey("needRefresh")) {
                    mNeedRefresh = getBackwardArguments().getBoolean("needRefresh");
                }

                if (getBackwardArguments().containsKey("orderId")) {
                    this.orderId = getBackwardArguments().getString("orderId");
                }

            }

        }

        if (mView == null) {
            mView = APIProxy.res().inflate(R.layout.layout_order_detail);
            initView();
        } else {
            ViewGroup parent = (ViewGroup) mView.getParent();
            if (parent != null) {
                parent.removeView(mView);
            }
        }

        return mView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        int width = (APIProxy.sys().getScreenWidth() - (int)(60*APIProxy.sys().getScreenDensity()))/2;
        int height = width;
        ViewGroup.LayoutParams lp = mOneCarPic.getLayoutParams();
        lp.width = width;
        lp.height = height;
        mOneCarPic.setLayoutParams(lp);

        ViewGroup.LayoutParams lp2 = mtwoCarPic.getLayoutParams();
        lp2.width = width;
        lp2.height = height;
        mtwoCarPic.setLayoutParams(lp2);
    }




    @Override
    public void onResume() {
        super.onResume();
        if (mNeedRefresh) {
            showLoadingDialog(true);
            requestData();
        }

    }

    /**
     * 拆分图片路径
     */

    private String[] getPic(String picUrl) {
        String[] sourceStrArray = null;
        if (!TextUtils.isEmpty(picUrl)) {
            sourceStrArray = picUrl.split(",");
        }
        return sourceStrArray;

    }

    /**
     * 填充车主信息
     */
    private void initViewChildDriverInfo(OrderDetailResponse orderDetailResponse) {
        mDriverName.setText(orderDetailResponse.data.carerNickname);
        mRatingBar.setRating(orderDetailResponse.data.carerStar);
        mDriverInfo.setText(orderDetailResponse.data.carColor + " " + orderDetailResponse.data.carBrand
                + " " + orderDetailResponse.data.carNumber);
        if (!TextUtils.isEmpty(orderDetailResponse.data.carPic)) {
            String str[] = getPic(orderDetailResponse.data.carPic);
            if (str != null) {
                for (int k = 0; k < str.length; k++) {
                    if (k == 0) {
                        initImageView(str[0], mOneCarPic);
                    }
                    if (k == 1) {
                        initImageView(str[1], mtwoCarPic);
                    }

                }
            }
        }
    }

    /**
     * 填充出发地、目的地信息
     */

    private void initViewFromAndToInfo(OrderDetailResponse orderDetailResponse) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(Long.parseLong(orderDetailResponse.data.startTime) * 1000);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        String startTime = simpleDateFormat.format(calendar.getTime());

        if (TimeUtil.isToday(calendar)) {
            mTimeTv.setText(
                    "今天 " + startTime);

        } else if (TimeUtil.isTomorrow(calendar)) {
            mTimeTv.setText(
                    "明天 " + startTime);

        } else if (TimeUtil.isAfter(calendar)) {
            mTimeTv.setText(
                    "后天 " + startTime);

        } else {
            mTimeTv.setText(getStrTime(orderDetailResponse.data.startTime));
        }

        mFromTV.setText(orderDetailResponse.data.startPlace);
        mToTv.setText(orderDetailResponse.data.arrivePlace);
        mFeeTv.setTextColor(APIProxy.res().getResources().getColor(R.color.carpool_text_gray_dack));

    }

    private Handler updateProgressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mTimerProgressBar.setProgress(mCount);
            if (mCount == 0) {
                isProcessThread = false;
                updateProgressHandler.removeCallbacks(updateProgressRunnable);
                updateProgressHandler.removeMessages(0);
                requestData();
            }
        }
    };

    private Runnable updateProgressRunnable = new Runnable() {

        public void run() {
            if (isProcessThread) {
                mSpareTime = mSpareTime - (mDelayMills / 1000);
                long totalTime = mPayEndTime - mPayStartTime;
                double proportion = (double)mSpareTime / totalTime;
                mCount = (int) (proportion * 100);
                if (mSpareTime <= 0 || mCount <= 0) {
                    isProcessThread = false;
                    mCount = 0;
                    updateProgressHandler.sendEmptyMessage(0);
                } else {
                    updateProgressHandler.sendEmptyMessage(0);
                    updateProgressHandler.postDelayed(updateProgressRunnable, mDelayMills);
                }
            }
        }
    };

    private void showProgressBar(Long spareTime) {
        mSpareTime = spareTime;
        long deltaTime = mPayEndTime - mPayStartTime;
        mDelayMills = deltaTime * 100;
        if (mPayEndTime - mCurrentSystem <= 0) {
            mCount = 0;
            mTimerProgressBar.setProgress(mCount);
        } else {
            //计算的时候需要先让结果保留小数部分
            long totalTime = mPayEndTime - mPayStartTime;
            double proportion = (double) mSpareTime / totalTime;
            mCount = (int) (proportion * 100);
            mTimerProgressBar.setProgress(mCount);
            isProcessThread = true;
            updateProgressHandler.removeCallbacks(updateProgressRunnable);
            updateProgressHandler.postDelayed(updateProgressRunnable, mDelayMills);
        }
    }


    private void initViewByOrderStatus(OrderDetailResponse orderDetailResponse) {

        initViewFromAndToInfo(orderDetailResponse);
        initViewChildDriverInfo(orderDetailResponse);
        mView.findViewById(R.id.star_kongbai).setVisibility(View.GONE);
        final String mobile = orderDetailResponse.data.mobile;
        mFeeTv.setText(orderDetailResponse.data.orderStatusDesc);
        mTimerProgressBar.setVisibility(View.GONE);
        mPayTipLin.setVisibility(View.VISIBLE);
        if (orderDetailResponse.data.orderStatusId == 7 || orderDetailResponse.data.orderStatusId == 21) {
            /**
             * 7.待支付
             * 21.车主取消已支付订单
             */
            if (orderDetailResponse.data.orderStatusId == 7) {
                StatisticsUtil.getInstance().addStatisticsOnline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_UNPAID);
            }
            mParentLin.addView(viewFromAndToInfo);
            mParentLin.addView(viewChildDriverInfo);

            if (orderDetailResponse.data.orderStatusId == 21) {
                mPayTV.setText("重新预约");
                mGoTo.setVisibility(View.VISIBLE);
                mGoTo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_PAY_PAGE,
                                StatisticsUtil.OFFLINE_ACT_RECREATE_ORDER_BT);
                        try {
                            Bundle bundle = new Bundle();
                            bundle.putString("history", "history");
                            APIProxy.navi().navigateTo(CarpoolHomePage.class, bundle, true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

                mDriverJoin.setVisibility(View.VISIBLE);
                mPayTipLin.setEnabled(true);
                mPayTipLin.setOnClickListener(new DriverJoinIn());
                mGoToContainLin.setVisibility(View.VISIBLE);

            } else {
                mOrderStatusLin.setVisibility(View.VISIBLE);
                mTimerGiftView.setVisibility(View.VISIBLE);
                mTimerGiftView.showAnimation();
                int payDisableTime = (int) (Long.parseLong(orderDetailResponse.data.payDisableTime) / 60);
                mOrderDesc.setText("车主已接单，请在" + payDisableTime + "分钟之内支付");
                mOrderStatusLin.setBackgroundColor(APIProxy.res().getResources().getColor(R.color.car_title_bg_color));
                mOrderDesc.setTextColor(APIProxy.res().getResources().getColor(R.color.carpool_blue));
                mTimerProgressBar.setVisibility(View.VISIBLE);
                mTitleHelper.setRightViewTextShow();
                mCurrentSystem = Long.parseLong(orderDetailResponse.data.currentTime);
                mPayEndTime = Long.parseLong(orderDetailResponse.data.payEndTime);
                mPayStartTime = Long.parseLong(orderDetailResponse.data.payStartTime);

                if (mPayEndTime - mCurrentSystem <= 0) {
                    requestData();
                } else {
                    updateProgressHandler.removeCallbacks(updateProgressRunnable);
                    updateProgressHandler.removeMessages(0);
                    showProgressBar(mPayEndTime - mCurrentSystem);
                }

                mPayTV.setText(
                        "立即支付" + (NumberUtil.subZeroAndDot(String.valueOf((double) orderDetailResponse.data
                                .price / 100)))
                                + "元");
                if (TextUtils.isEmpty(orderDetailResponse.data.firstDesc)) {
                    mPayTipLin.setVisibility(View.GONE);
                } else {
                    mPatTip.setVisibility(View.VISIBLE);
                    mPatTip.setText(orderDetailResponse.data.firstDesc);
                }
                mGoTo.setVisibility(View.VISIBLE);
                mGoTo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        gotoPay();
                    }
                });
                mGoToContainLin.setVisibility(View.VISIBLE);

            }

        } else if (orderDetailResponse.data.orderStatusId == 8 || orderDetailResponse.data.orderStatusId ==
                14 || orderDetailResponse.data.orderStatusId ==
                15 || orderDetailResponse.data.orderStatusId == 6 || orderDetailResponse.data.orderStatusId
                == 4 || orderDetailResponse.data.orderStatusId == 5 || orderDetailResponse.data
                .orderStatusId == 22
                ) {
            /**
             * 14.订单取消，待车主确认
             * 15.订单取消，等待客服解决
             * 6.待退款
             * 4.退款成功
             * 5.退款失敗
             * 8.抢单成功，支付超时
             * 22.车主确认取消
             */
            mParentLin.addView(viewFromAndToInfo);
            mParentLin.addView(viewChildDriverInfo);

            if (orderDetailResponse.data.orderStatusId == 8) {
                mOrderStatusLin.setVisibility(View.VISIBLE);
                mOrderStatusLin.setVisibility(View.VISIBLE);
                mTimerGiftView.setVisibility(View.GONE);
                mOrderDesc.setText("支付超时,订单已取消");
                mOrderStatusLin.setBackgroundColor(APIProxy.res().getResources().getColor(R.color.pay_time_out_gray));
                mOrderDesc.setTextColor(APIProxy.res().getResources().getColor(R.color.text_white));
                if (TextUtils.isEmpty(orderDetailResponse.data.firstDesc)) {
                    mPayTipLin.setVisibility(View.GONE);
                } else {
                    mPatTip.setVisibility(View.VISIBLE);
                    mPatTip.setText(orderDetailResponse.data.firstDesc);
                }

            } else {
                mDriverJoin.setVisibility(View.VISIBLE);
                mPayTipLin.setEnabled(true);
                mPayTipLin.setOnClickListener(new DriverJoinIn());
            }
            mPayTV.setText("重新预约");
            mGoTo.setVisibility(View.VISIBLE);
            mGoTo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_PAY_PAGE,
                            StatisticsUtil.OFFLINE_ACT_RECREATE_ORDER_BT);
                    try {
                        Bundle bundle = new Bundle();
                        bundle.putString("history", "history");
                        APIProxy.navi().navigateTo(CarpoolHomePage.class, bundle, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            mGoToContainLin.setVisibility(View.VISIBLE);

        } else if (orderDetailResponse.data.orderStatusId == 10 || orderDetailResponse.data.orderStatusId
                == 11 || orderDetailResponse.data.orderStatusId == 16) {
            /**
             * 10.支付成功，待成单
             * 11.支付成功，已成单
             * 16.评论成功，订单完成
             */
            mParentLin.addView(viewFromAndToInfo);
            mParentLin.addView(viewChildDriverInfo);
            final int statusId = orderDetailResponse.data.orderStatusId;
            if (statusId == 10 || statusId == 11) {
                mTitleHelper.setRightViewTextShow();
                StatisticsUtil.getInstance().addStatisticsOnline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_PAID);
                mPayTV.setText("确认上车");
                mGoTo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //TODO 确认上车
                        StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_PAGE,
                                StatisticsUtil.OFFLINE_ACT_FINISH_INFO_BT);
                        CarpoolAlertDialog.Builder builder = new CarpoolAlertDialog.Builder(getActivity());
                        builder.setTitle("小主确认搭乘后，车费将转账给车主，请于顺风车服务结束后确认");
                        builder.setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                //直接结束dialog
                            }
                        });
                        builder.setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                StatisticsUtil.getInstance()
                                        .addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_PAID,
                                                StatisticsUtil.OFFLINE_ACT_CONFIRM_GETON_BT);
                                if (statusId == 10) {
                                    ToastForCarpool.show(mActivity, "支付成功，待成单");
                                } else {
                                    goBus();
                                }
                            }
                        });
                        builder.create().show();
                    }
                });
                mCallPhone.setVisibility(View.VISIBLE);
                mCallPhone.setOnClickListener(new CallCarer(mobile));
                if (TextUtils.isEmpty(orderDetailResponse.data.firstDesc)) {
                    mPayTipLin.setVisibility(View.GONE);
                } else {
                    mPatTip.setVisibility(View.VISIBLE);
                    mPatTip.setText(orderDetailResponse.data.firstDesc);
                }
            } else {
                mPayTV.setText("再订一单");
                mGoTo.setVisibility(View.VISIBLE);
                mGoTo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //TODO 再订一单
                        try {
                            APIProxy.navi().navigateTo(CarpoolHomePage.class, null, true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

                mDriverJoin.setVisibility(View.VISIBLE);
                mPayTipLin.setEnabled(true);
                mPayTipLin.setOnClickListener(new DriverJoinIn());
            }
            mGoToContainLin.setVisibility(View.VISIBLE);

        } else if (orderDetailResponse.data.orderStatusId == 12) {
            /**
             * 12.支付成功，已确认上车，待评价
             */
            mParentLin.addView(viewFromAndToInfo);
            mParentLin.addView(viewChildDriverInfo);
            mDriverJoin.setVisibility(View.VISIBLE);
            mPayTipLin.setEnabled(true);
            mPayTipLin.setOnClickListener(new DriverJoinIn());
            mView.findViewById(R.id.star_kongbai).setVisibility(View.VISIBLE);
            mPayTV.setText("评价车主");
            mGoTo.setVisibility(View.VISIBLE);
            mGoTo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //TODO 评价车主
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(OrderDetailResponse.class.getName(),
                                    mOrderDetailResponse);
                            APIProxy.navi().navigateTo(CreateCarerCommentPage.class, bundle);
                        }
            });
            mGoToContainLin.setVisibility(View.VISIBLE);

        } else if (orderDetailResponse.data.orderStatusId == 3 || orderDetailResponse.data.orderStatusId ==
                13 || orderDetailResponse.data.orderStatusId == 18 || orderDetailResponse.data
                .orderStatusId == 1) {
            /**
             * 3.无人接单，抢单超时
             * 13.订单取消未支付
             * 18.车主订单取消，未支付
             * 1.下单失败
             */
            viewChildDriverInfo.setVisibility(View.GONE);
            mParentLin.addView(viewFromAndToInfo);
            if (orderDetailResponse.data.isRealPic == 0) {
                mCompleteInfo.setVisibility(View.VISIBLE);
                mPayTipLin.setEnabled(true);
                mPayTipLin.setOnClickListener(new CompleteUserInfo());
            } else {
                mDriverJoin.setVisibility(View.VISIBLE);
                mPayTipLin.setEnabled(true);
                mPayTipLin.setOnClickListener(new DriverJoinIn());
            }

            mFeeTv.setTextColor(APIProxy.res().getResources().getColor(R.color.order_erro_red));
            mPayTV.setText("重新预约");
            mGoTo.setVisibility(View.VISIBLE);
            mGoTo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_PAY_PAGE,
                            StatisticsUtil.OFFLINE_ACT_RECREATE_ORDER_BT);
                    try {
                        APIProxy.navi().navigateTo(CarpoolHomePage.class, null, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            mGoToContainLin.setVisibility(View.VISIBLE);

        } else {

        }

    }

    private class GetDataTask extends AsyncTask<Void, Void, LinearLayout> {
        @Override
        protected LinearLayout doInBackground(Void... params) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(LinearLayout result) {
            mTimerProgressBar.setVisibility(View.GONE);
            mOrderStatusLin.setVisibility(View.GONE);
            mParentLin.removeAllViews();

            mCallPhone.setVisibility(View.GONE);
            mPatTip.setVisibility(View.GONE);
            mDriverJoin.setVisibility(View.GONE);
            mCompleteInfo.setVisibility(View.GONE);
            mPayTipLin.setEnabled(false);

            mGoToContainLin.setVisibility(View.GONE);
            viewChildDriverInfo.setVisibility(View.VISIBLE);
            initViewByOrderStatus(mOrderDetailResponse);
            mPullToRefreshScrollView.onRefreshComplete();
            super.onPostExecute(result);
        }
    }

    /**
     * 根据orderId请求当前对应的reponse
     */
    private void requestData() {
        if (!checkNetworkStatus(true)) {
            mParentLin.removeAllViews();
            mTimerProgressBar.setVisibility(View.GONE);
            mParentLin.removeAllViews();
            mTitleHelper.setRightViewHide();
            mGoToContainLin.setVisibility(View.GONE);
            mOrderStatusLin.setVisibility(View.GONE);
            mPullToRefreshScrollView.onRefreshComplete();
            return;
        }

       /* mCallPhone.setVisibility(View.GONE);
        mDriverJoin.setVisibility(View.GONE);
        mCompleteInfo.setVisibility(View.GONE);
        mPayTipLin.setEnabled(false);*/

        //mOrderStatusLin.setVisibility(View.GONE);
        //mGoToContainLin.setVisibility(View.GONE);
        mTitleHelper.setRightView("取消订单", this);
        mTitleHelper.setRightViewHide();
        //mTimerProgressBar.setVisibility(View.GONE);

        OrderDetailData orderDetailData = new OrderDetailData(mActivity);
        orderDetailData.setOrderId(orderId);
        orderDetailData.post(new IDataStatusChangedListener<OrderDetailResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderDetailResponse> comNetData,
                                            OrderDetailResponse orderDetailResponse,
                                            int i) {
                if (orderDetailResponse != null && orderDetailResponse.data != null) {
                    if (orderDetailResponse.errorNo == 0) {
                        mOrderDetailResponse = orderDetailResponse;
                        // initViewByOrderStatus(orderDetailResponse);
                        new GetDataTask().execute();
                    } else if (orderDetailResponse.errorNo == 1030) {
                        mTimerProgressBar.setVisibility(View.GONE);
                        mTitleHelper.setRightViewHide();
                       // mPullToRefreshScrollView.setVisibility(View.GONE);
                        mParentLin.removeAllViews();
                        mGoToContainLin.setVisibility(View.GONE);
                        mOrderStatusLin.setVisibility(View.GONE);
                        ToastForCarpool.show(mActivity, "该账号中未找到此订单，请尝试其他账号");

                    } else {
                        mTimerProgressBar.setVisibility(View.GONE);
                        //mPullToRefreshScrollView.setVisibility(View.GONE);
                        mParentLin.removeAllViews();
                        mTitleHelper.setRightViewHide();
                        mGoToContainLin.setVisibility(View.GONE);
                        mOrderStatusLin.setVisibility(View.GONE);
                        ToastForCarpool.show(mActivity, "网络异常,请下拉刷新试试");

                    }
                } else {
                    mTimerProgressBar.setVisibility(View.GONE);
                    //mPullToRefreshScrollView.setVisibility(View.GONE);
                    mParentLin.removeAllViews();
                    mTitleHelper.setRightViewHide();
                    mGoToContainLin.setVisibility(View.GONE);
                    ToastForCarpool.show(mActivity, "网络异常,请下拉刷新试试");

                }
                mPullToRefreshScrollView.onRefreshComplete();
                showLoadingDialog(false);
            }
        });

    }

    public String getStrTime(String time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = null;
        if (time.equals("")) {
            return "";
        }
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long loc_time = Long.valueOf(time);
        re_StrTime = sdf.format(new Date(loc_time * 1000L));
        return re_StrTime;
    }

    private void initView() {
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(this);
        mTitleHelper.setCenterView("订单详情");
        mTitleHelper.setRightViewHide();

        /**
         * 主View
         */
        mParentLin = (LinearLayout) mView.findViewById(R.id.add_child_lin);
        mPayTV = (TextView) mView.findViewById(R.id.pay_now);
        mGoTo = (LinearLayout) mView.findViewById(R.id.lin_go_to);
        mGoToContainLin = (LinearLayout) mView.findViewById(R.id.scroll_bootom_lin);
        mGoToContainLin.setVisibility(View.GONE);
        mOrderStatusLin = (LinearLayout) mView.findViewById(R.id.plug_order_status);
        mOrderStatusLin.setVisibility(View.GONE);
        mTimerGiftView = (GifView) mView.findViewById(R.id.gif_shizhong);
        mTimerGiftView.setGifImage(R.drawable.shizhong_icon);
        mOrderDesc = (TextView) mView.findViewById(R.id.tv_order_desc);
        mTimerProgressBar = (ProgressBar) mView.findViewById(R.id.timer_progressbar);
        mTimerProgressBar.setVisibility(View.GONE);
        mPullToRefreshScrollView = (PullToRefreshScrollView) mView.findViewById(R.id.scroll_bootom);
        mPullToRefreshScrollView.getLoadingLayoutProxy().setPullLabel("下拉加载更多数据");
        mPullToRefreshScrollView.getLoadingLayoutProxy().setRefreshingLabel("加载中...");
        mPullToRefreshScrollView.getLoadingLayoutProxy().setReleaseLabel("松开加载更多数据");
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                requestData();
            }
        });
        //底层
        mPayTipLin = (LinearLayout) mView.findViewById(R.id.lin_pay_tip);
        //支付提示
        mPatTip = (TextView) mView.findViewById(R.id.tv_pay_tip);
        //车主加盟
        mDriverJoin = (TextView) mView.findViewById(R.id.dirver_join);
        //完善资料
        mCompleteInfo = (TextView) mView.findViewById(R.id.tv_complete_info);
        /**
         * 司机相关信息
         */
        viewChildDriverInfo = APIProxy.res().inflate(R.layout.plug_detail_bus_info);

        mDriverName = (TextView) viewChildDriverInfo.findViewById(R.id.plug_driver_name);
        mRatingBar = (RatingBar) viewChildDriverInfo.findViewById(R.id.plug_driver_ratingbar);
        mDriverInfo = (TextView) viewChildDriverInfo.findViewById(R.id.plug_driver_info);
        mOneCarPic = (ImageView) viewChildDriverInfo.findViewById(R.id.plug_driver_oneimg);
        mtwoCarPic = (ImageView) viewChildDriverInfo.findViewById(R.id.plug_driver_twoimg);
        //联系车主
        mCallPhone = (LinearLayout) viewChildDriverInfo.findViewById(R.id.call_phone);
        mCallPhone.setVisibility(View.GONE);
        viewChildDriverInfo.findViewById(R.id.lin_driver_pingjia).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_UNPAID,
                        StatisticsUtil.OFFLINE_ACT_DRIVER_COMMENT_BT);
                Bundle b = new Bundle();
                b.putSerializable(OrderDetailResponse.class.getName(), mOrderDetailResponse);
                APIProxy.navi().navigateTo(EvaluateDriverPage.class, b);
            }
        });

        /**
         * 出发地，目的地相关信息
         */
        viewFromAndToInfo = APIProxy.res().inflate(R.layout.plug_detail_distance);

        mTimeTv = (TextView) viewFromAndToInfo.findViewById(R.id.plug_detail_time);
        mFeeTv = (TextView) viewFromAndToInfo.findViewById(R.id.des_fee);
        mFromTV = (TextView) viewFromAndToInfo.findViewById(R.id.plug_detail_from);
        mToTv = (TextView) viewFromAndToInfo.findViewById(R.id.plug_detail_to);
        initImageLoader();

        //mParentLin.addView(viewFromAndToInfo);
        //mParentLin.addView(viewChildDriverInfo);
    }

    private void initImageLoader() {
        mImageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .cacheInMemory()
                .cacheOnDisc()
                .showImageForEmptyUri(APIProxy.res().getDrawable(R.drawable.gray_tangle))
                .cacheInMemory().build();
    }

    private void initImageView(String url, ImageView arg1) {
        //  String imgUrlString = url;
        mImageLoader.init(ImageLoaderConfiguration.createDefault(APIProxy.res().getBaseActivity()));
        String finalUrl = "";
        finalUrl = url;
        mImageLoader.displayImage(finalUrl, arg1, options, new SimpleImageLoadingListener());

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_view:
                Bundle bundleForOrderList = prepareBundleForBackOrderList();
                if (bundleForOrderList == null) {
                    goBack();
                } else {
                    goBack(bundleForOrderList);
                }
                break;
            case R.id.right_view:
                if (mOrderDetailResponse != null && mOrderDetailResponse.data != null) {
                    if (mOrderDetailResponse.data.orderStatusId == 7) {
                        StatisticsUtil.getInstance()
                                .addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_UNPAID,
                                        StatisticsUtil.OFFLINE_ACT_CANCEL_BT);
                    }
                    if (mOrderDetailResponse.data.orderStatusId == 10
                            || mOrderDetailResponse.data.orderStatusId == 11) {
                        StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_PAID,
                                StatisticsUtil.OFFLINE_ACT_CANCEL_BT);
                    }
                }
                Bundle bundle = new Bundle();
                bundle.putString("orderId", orderId);
                APIProxy.navi().navigateTo(CancelOrderPage.class, bundle);
                break;

        }

    }

    private Bundle prepareBundleForBackOrderList() {
        Bundle tempBundleForOrderList = new Bundle();
        tempBundleForOrderList = getArguments();
        tempBundleForOrderList.putSerializable(OrderDetailResponse.class.getName(), mOrderDetailResponse);
        return tempBundleForOrderList;
    }

    /**
     * 确认上车
     */
    public void goBus() {
        OrderFinishData orderFinishData = new OrderFinishData(mActivity);
        orderFinishData.setBduss(UserInfoSetting.getBduss());
        orderFinishData.setOrderId(this.orderId);
        orderFinishData.post(new IDataStatusChangedListener<OrderFinishResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderFinishResponse> comNetData,
                                            OrderFinishResponse orderFinishResponse,
                                            int i) {
                if (orderFinishResponse != null) {
                    if (orderFinishResponse.getErrorNo() == 0) {
                        //requestData();
                        if (mOrderDetailResponse != null) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(OrderDetailResponse.class.getName(),
                                    mOrderDetailResponse);
                            APIProxy.navi().navigateTo(CreateCarerCommentPage.class, bundle);
                        } else {
                            ToastForCarpool.show(mActivity, "网络异常,请稍候再试");
                        }

                    } else if (orderFinishResponse.getErrorNo() == 1003) {
                        ToastForCarpool.show(mActivity, "未登录");
                    } else if (orderFinishResponse.getErrorNo() == 1004) {
                        ToastForCarpool.show(mActivity, "没有权限");

                    } else if (orderFinishResponse.getErrorNo() == 7001) {
                        ToastForCarpool.show(mActivity, "错误的订单状态");

                    }
                }

            }
        });

    }

    /**
     * 去支付
     */
    private void gotoPay() {
        showLoadingDialog(true);
        if (!checkNetworkStatus(true)) {
            return;
        }
        OrderDetailData orderDetailData = new OrderDetailData(mActivity);
        orderDetailData.setOrderId(this.orderId);
        orderDetailData.post(new IDataStatusChangedListener<OrderDetailResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderDetailResponse> comNetData,
                                            OrderDetailResponse orderDetailResponse,
                                            int i) {
                showLoadingDialog(false);
                if (orderDetailResponse != null && orderDetailResponse.data != null) {
                    if (orderDetailResponse.data.orderStatusId == 7) {
                        Bundle b = new Bundle();
                        b.putString("orderId", mOrderDetailResponse.data.orderId);
                        APIProxy.navi().navigateTo(OrderPayPage.class, b);
                    } else if (orderDetailResponse.data.orderStatusId == 8 || orderDetailResponse.data.orderStatusId
                            == 21) {
                        /**
                         * 8.抢单成功，支付超时
                         * 21.车主取消
                         */
                        mPayTV.setText("重新预约");
                        mGoTo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_PAY_PAGE,
                                        StatisticsUtil.OFFLINE_ACT_RECREATE_ORDER_BT);
                                try {
                                    Bundle bundle = new Bundle();
                                    bundle.putString("history", "history");
                                    APIProxy.navi().navigateTo(CarpoolHomePage.class, bundle, true);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        if (orderDetailResponse.data.orderStatusId == 8) {
                            ToastForCarpool.show(mActivity, "支付超时，订单取消，请您重新预订");
                        } else {
                            ToastForCarpool.show(mActivity, "车主取消订单，请您重新预订");
                        }

                    } else {
                        //TODO 去支付的时候，验证此时订单失效
                        requestData();
                    }
                } else {
                    ToastForCarpool.show(mActivity, "网络异常,请稍后再试");

                }

            }
        });

    }

    @Override
    public boolean onBackPressed() {
        Bundle bundleForOrderList = prepareBundleForBackOrderList();
        if (bundleForOrderList == null) {
            goBack();
        } else {
            goBack(bundleForOrderList);
        }
        return true;
    }

    /**
     * 联系车主
     */
    public class CallCarer implements View.OnClickListener {
        String mobile = "";

        public CallCarer(String mobile) {
            this.mobile = mobile;
        }

        @Override
        public void onClick(View view) {
            StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.DA_SRC_VALUE_ORDER_DETAIL_PAID, StatisticsUtil.OFFLINE_ACT_CANTACT_DRIVER_BT);
            if (TextUtils.isEmpty(mobile)) {
                return;
            }
            CarpoolOkCancelDialog.showDialog(
                    (FragmentActivity) APIProxy.res().getBaseActivity(),
                    "",
                    "确认拨打车主电话:\n" + mobile + "?",
                    "呼叫",
                    "取消",
                    new View.OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            APIProxy.sys().dial(mobile);
                        }
                    });
        }
    }

    /**
     * 车主加盟
     */
    public class DriverJoinIn implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            StatisticsUtil.getInstance().addStatisticsOffline(StatisticsUtil.OFFLINE_ACT_JOIN_DRIVER_TEAM, "");
            if (!checkNetworkStatus(true)) {
                return;
            }
            if (Config.MONKEY_OPEN) {
                return;
            }
            UserInfoSetting.goToWebShell(URLModel.CARE_JOIN_URL);
        }
    }

    /**
     * 完善资料
     */
    public class CompleteUserInfo implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            Bundle bundleForUserInfo = new Bundle();
            bundleForUserInfo.putString("orderId", mOrderDetailResponse.data.orderId);
            APIProxy.navi().navigateTo(UserInfoPage.class, bundleForUserInfo);
        }
    }

}
